package com.kunpan.admin.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kunpan.admin.common.redis.RedisMessageReceiver;
import com.kunpan.admin.constant.RedisMessage;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * redis配置
 *
 * @author ruoyi
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 配置 Lettuce 连接工厂（替换默认的 LettuceConnectionFactory）
     */
//    @Bean
//    public LettuceConnectionFactory redisConnectionFactory() {
//        // 配置 Lettuce 客户端选项
//        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
//                .commandTimeout(timeout) // 命令超时时间
//                .clientOptions(ClientOptions.builder()
//                        .autoReconnect(true)      // 启用自动重连
//                        .disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS) // 断开时拒绝命令
//                        .socketOptions(SocketOptions.builder()
//                                .keepAlive(true)  // 启用 TCP KeepAlive
//                                .tcpNoDelay(true)
//                                .build())
//                        .build())
//                .build();
//
//        // 创建 Lettuce 连接工厂
//        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
//        //设置密码
//        redisStandaloneConfiguration.setPassword(password);
//        redisStandaloneConfiguration.setDatabase(database);
//        return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
//    }
    @Bean
//    @SuppressWarnings(value = { "unchecked", "rawtypes" })RedisConnectionFactory
    @SuppressWarnings("all")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }


    /**
     * 消息监听器容器
     */
    @Bean
    @SuppressWarnings("all")
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter
    ) {
        //创建监听器容器
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        //设置连接工厂
        container.setConnectionFactory(connectionFactory);

//        Jackson2JsonRedisSerializer seria = new Jackson2JsonRedisSerializer(Object.class);
//        container.setTopicSerializer(seria);
        //添加监听器，设置主题：FILE_UPLOAD_SUCCESS，基于模式(pattern)的发布/订阅
        container.addMessageListener(listenerAdapter, new PatternTopic(RedisMessage.FILE_UPLOAD_SUCCESS));
        return container;
    }

    /**
     * 消息适配器
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(RedisMessageReceiver receiver) {
        //通过反射的方式拿到RedisMessageReceiver中的handleMessage方法
        MessageListenerAdapter adapter  = new MessageListenerAdapter(receiver, "handleMessage");
        adapter.setSerializer(new FastJson2JsonRedisSerializer<>(Object.class));
        return adapter;
    }

    @Bean
    public DefaultRedisScript<Long> limitScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    /**
     * 限流脚本
     */
    private String limitScriptText() {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }
}
